﻿using System;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Configuration;
using System.Web;
using System.Globalization;
using System.IO;
using oAuth;


namespace Twitter_Plugin
{
    public partial class Main : Form
    {
        static oAuthTwitter oAuth = new oAuthTwitter();
        //Twitter ConsumerKey and Secret
        static string twConsumerKey = "";
        static string twConsumerKeySecret = "";
        //TwitPic API
        static string TwitPicAPIKey = "";


        public Main()
        {
            InitializeComponent();
        }
        private void Main_Load(object sender, EventArgs e)
        {

            if (oAuth.Token.Length > 0)
            {
                grpPIN.Enabled = false;
                grpTweet.Enabled = true;

            }
            else
            {
                grpPIN.Enabled = true;
            }
        }

        private void btnSelectPhoto_Click(object sender, EventArgs e)
        {
            openFileDialog1.FileName = "";

            openFileDialog1.ShowDialog();
            if (System.IO.File.Exists(openFileDialog1.FileName))
            {
                picturePreview.ImageLocation = openFileDialog1.FileName;
            }
        }

        private void btnGetPIN_Click(object sender, EventArgs e)
        {

            oAuth.ConsumerKey = twConsumerKey;
            oAuth.ConsumerSecret = twConsumerKeySecret;

            //Get the authorization url.
            Uri url = new Uri(oAuth.AuthorizationLinkGet());

            oAuth.Token = HttpUtility.ParseQueryString(url.Query)["oauth_token"];


            //Copy the authorization url to the clip board
            Clipboard.SetText(url.ToString());

            System.Diagnostics.Process.Start(url.ToString());


        }


        private void txtVerifyPIN_Click(object sender, EventArgs e)
        {

            try
            {
                if (txtVerifyPIN.Text.Length > 0)
                {

                    oAuth.AccessTokenGet(oAuth.Token, txtVerifyPIN.Text);

                    grpPIN.Enabled = false;
                    grpTweet.Enabled = true;

                }

            }
            catch (Exception err)
            {

                MessageBox.Show(err.Message);
            }

        }

        private void btnTweet_Click(object sender, EventArgs e)
        {
            string normalizedString, normalizedParameters;
            string TwitPicResp;
            string TwitPicURL;
            string contentEncoding = "iso-8859-1";

            string boundary = Guid.NewGuid().ToString();
            HttpWebRequest request;

            string timestamp;

            string nonce;

            string signature;



            if (txtMessage.Text.Length > 0)
            {
                //Generate a time stamp
                timestamp = oAuth.GenerateTimeStamp();

                //Generate nonce
                nonce = oAuth.GenerateNonce();

                //Generate Signature for authorization with Twitter
                signature = oAuth.GenerateSignature(new Uri("https://api.twitter.com/1/account/verify_credentials.json"), twConsumerKey, twConsumerKeySecret, oAuth.Token, oAuth.TokenSecret, "", "GET", timestamp, nonce, out normalizedString, out normalizedParameters);
                signature = oAuth.UrlEncode(signature);


                //Build the TwitPic request
                request = (HttpWebRequest)WebRequest.Create("http://api.twitpic.com/2/upload.json");
                var oauthSignaturePattern = "OAuth realm=\"{0}\", oauth_consumer_key=\"{1}\", oauth_signature_method=\"HMAC-SHA1\", oauth_token=\"{2}\", oauth_timestamp=\"{3}\", oauth_nonce=\"{4}\", oauth_version=\"1.0\", oauth_signature=\"{5}\"";

                var authenticationRealm = "http://api.twitter.com/";

                request.PreAuthenticate = true;

                request.AllowWriteStreamBuffering = true;

                request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);

                request.Headers.Add("X-Auth-Service-Provider", "http://twitter.com/account/verify_credentials.xml");

                var authorizationHeader = string.Format(

                                            CultureInfo.InvariantCulture,

                                            oauthSignaturePattern,

                                            authenticationRealm,

                                            twConsumerKey,

                                            ConfigurationManager.AppSettings["OAuthToken"].ToString(),

                                            timestamp,

                                            nonce,

                                            signature);

                request.Headers.Add("X-Verify-Credentials-Authorization", authorizationHeader);

                request.Method = "POST";


                //Upload the media to TwitPic
                var header = string.Format("--{0}", boundary);

                var footer = string.Format("--{0}--", boundary);

                var contents = new StringBuilder();

                contents.AppendLine(header);


                string fileContentType = MimeType(picturePreview.ImageLocation);

                string fileHeader = string.Format("Content-Disposition: file; name=\"{0}\"; filename=\"{1}\"", "media", Path.GetFileName(picturePreview.ImageLocation));

                string fileData = Encoding.GetEncoding(contentEncoding).GetString(File.ReadAllBytes(picturePreview.ImageLocation));



                contents.AppendLine(fileHeader);

                contents.AppendLine(string.Format("Content-Type: {0}", fileContentType));

                contents.AppendLine();

                contents.AppendLine(fileData);



                contents.AppendLine(header);

                contents.AppendLine(string.Format("Content-Disposition: form-data; name=\"{0}\"", "key"));

                contents.AppendLine();

                contents.AppendLine(TwitPicAPIKey);



                contents.AppendLine(header);

                contents.AppendLine(String.Format("Content-Disposition: form-data; name=\"{0}\"", "message"));

                contents.AppendLine();

                contents.AppendLine(txtMessage.Text);

                contents.AppendLine(footer);

                byte[] bytes = Encoding.GetEncoding(contentEncoding).GetBytes(contents.ToString());

                request.ContentLength = bytes.Length;


                using (var requestStream = request.GetRequestStream())
                {

                    requestStream.Write(bytes, 0, bytes.Length);


                    using (var twitpicResponse = (HttpWebResponse)request.GetResponse())
                    {

                        using (var reader = new StreamReader(twitpicResponse.GetResponseStream()))
                        {
                            requestStream.Dispose();

                            TwitPicResp = twitpicResponse.StatusCode + ": " + reader.ReadToEnd();
                        }
                    }
                }

                //Read the URL from the TwitPic JSON response
                TwitPicURL = TwitPicResp.Substring(TwitPicResp.IndexOf("http"), TwitPicResp.IndexOf("\"", TwitPicResp.IndexOf("http")) - TwitPicResp.IndexOf("http")).Replace("\\", "");


                oAuth.ConsumerKey = twConsumerKey;
                oAuth.ConsumerSecret = twConsumerKeySecret;

                //POST to Twitter
                string url = "http://twitter.com/statuses/update.xml";
                string xml = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, url, "status=" + oAuth.UrlEncode(txtMessage.Text + " " + TwitPicURL));


                MessageBox.Show(TwitPicURL);

                MessageBox.Show(xml);

            }
        }

        //A function to detect the file's Mime Type
        private string MimeType(string Filename)
        {
            string mime = "application/octetstream";
            string ext = System.IO.Path.GetExtension(Filename).ToLower();
            Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
            if (rk != null && rk.GetValue("Content Type") != null)
                mime = rk.GetValue("Content Type").ToString();
            return mime;
        }

    }
}
